package com.qyhl.module_practice.map.sign;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeAcitivityBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_SIGN_HOME)
public class PracticeSignHomeActivity extends BaseActivity implements PracticeSignHomeContract.PracticeSignHomeView
        , AMap.OnMapLoadedListener, LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, GeocodeSearch.OnGeocodeSearchListener {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.head_icon)
    RoundedImageView headIcon;
    @BindView(R2.id.name)
    TextView name;
    @BindView(R2.id.date)
    TextView date;
    @BindView(R2.id.sign_in_dot)
    RoundedImageView signInDot;
    @BindView(R2.id.sign_in_txt)
    TextView signInTxt;
    @BindView(R2.id.sign_in_time)
    TextView signInTime;
    @BindView(R2.id.sign_in_address)
    TextView signInAddress;
    @BindView(R2.id.divider)
    ImageView divider;
    @BindView(R2.id.sign_in_btn)
    TextView signInBtn;
    @BindView(R2.id.sign_in_tip)
    TextView signInTip;
    @BindView(R2.id.sign_in_area)
    TextView signInArea;
    @BindView(R2.id.sign_in_location)
    TextView signInLocation;
    @BindView(R2.id.sign_in_restart_location)
    TextView signInRestartLocation;
    @BindView(R2.id.index_view)
    View indexView;
    @BindView(R2.id.sign_out_dot)
    RoundedImageView signOutDot;
    @BindView(R2.id.sign_out_txt)
    TextView signOutTxt;
    @BindView(R2.id.sign_out_time)
    TextView signOutTime;
    @BindView(R2.id.sign_out_address)
    TextView signOutAddress;
    @BindView(R2.id.sign_out_btn)
    TextView signOutBtn;
    @BindView(R2.id.sign_out_tip)
    TextView signOutTip;
    @BindView(R2.id.sign_out_area)
    TextView signOutArea;
    @BindView(R2.id.sign_out_location)
    TextView signOutLocation;
    @BindView(R2.id.sign_out_restart_location)
    TextView signOutRestartLocation;
    @BindView(R2.id.map)
    MapView mMapView;
    @BindView(R2.id.map_layout)
    RelativeLayout mapLayout;
    @BindView(R2.id.current_location)
    TextView currentLocation;
    @BindView(R2.id.sign_btn)
    TextView signBtn;
    @BindView(R2.id.title_name)
    TextView titleName;

    private PracticeAcitivityBean mData;

    private String locationAddress;

    private AMap aMap;

    private Circle aCircle;
    /**
     * 声明AMapLocationClient类对象
     */
    public AMapLocationClient mLocationClient = null;
    /**
     * 声明AMapLocationClientOption对象
     */
    public AMapLocationClientOption mLocationOption = null;

    private GeocodeSearch geocoderSearch;

    private LocationSource.OnLocationChangedListener mListener;

    private Timer timer;
    private TimerTask timerTask;

    private String beforeTime;

    private PracticeSignHomePresenter mPresenter;

    private LatLng latLng;

    private LatLng mLatLng;

    private LatLonPoint latLonPoint;

    private Marker marker = null;

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_sign_home;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }


    @Override
    protected void init() {
        BusFactory.getBus().register(this);
        mData = (PracticeAcitivityBean) getIntent().getSerializableExtra("bean");
        title.setText(mData.getName());
        mPresenter = new PracticeSignHomePresenter(this);

        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
            aMap.setOnMarkerClickListener(this);
            aMap.setLocationSource(this);
        }

        if (geocoderSearch == null) {
            try {
                geocoderSearch = new GeocodeSearch(this);
            } catch (AMapException e) {
                e.printStackTrace();
            }
            geocoderSearch.setOnGeocodeSearchListener(this);
        }

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.showMyLocation(true);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);

        Glide.with(this)
                .load(mData.getVol().getLogo())
                .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                .into(headIcon);

        name.setText(mData.getVol().getName());

        date.setText(DateUtils.getYyyyMMDD());

        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        };


        setView();
    }

    @SuppressLint("SetTextI18n")
    private void setView() {
        titleName.setText("GPS定位签到");

        if (mData.getVolSignInfo().getIsSign() == 0) {
            signInBtn.setVisibility(View.VISIBLE);
            signInTip.setVisibility(View.VISIBLE);
            signInLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signInBtn.setText(spanUtils.create());

            signInTip.setText("请稍后");
            signInLocation.setText("暂未获取到定位");
        } else {
            signOutBtn.setVisibility(View.VISIBLE);
            signOutTip.setVisibility(View.VISIBLE);
            signOutLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signOutBtn.setText(spanUtils.create());

            signOutTip.setText("请稍后");
            signOutLocation.setText("暂未获取到定位");
        }
        if (aCircle != null) {
            aMap.clear();
        }
        if (mData.getActSignType() == 0) {  //0 普通签到   1 连续签到
            signInTxt.setText("签到时间：" + DateUtils.translateToHHmmss(mData.getRegistrationStart()));
            signOutTxt.setText("签退时间：" + DateUtils.translateToHHmmss(mData.getRegistrationDeadline()));
        } else {
            signInTxt.setVisibility(View.GONE);
            signOutTxt.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
        }

        if (mData.getVolSignInfo().getIsSign() == 0) { //未签到
            if (StringUtils.isNotEmpty(mData.getSignInLatitude())) {
                latLng = new LatLng(Double.parseDouble(mData.getSignInLatitude()), Double.parseDouble(mData.getSignInLongitude()));
                latLonPoint = new LatLonPoint(Double.parseDouble(mData.getSignInLatitude()), Double.parseDouble(mData.getSignInLongitude()));
                aCircle = aMap.addCircle(new CircleOptions()
                        .center(latLng)
                        .radius(mData.getSignInRadius())
                        .fillColor(Color.argb(85, 240, 137, 135))
                        .strokeColor(Color.argb(100, 240, 137, 135))
                        .strokeWidth(1));
            }

            signInDot.setImageResource(R.color.global_black_lv4);
            signBtn.setText("立即签到");
            signBtn.setEnabled(true);

            signInBtn.setVisibility(View.VISIBLE);
            signInRestartLocation.setVisibility(View.VISIBLE);
            signInArea.setVisibility(View.GONE);
            signInLocation.setVisibility(View.VISIBLE);
            signInTip.setVisibility(View.VISIBLE);

            divider.setImageResource(R.color.practice_divider);

            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(30, true).setBold();
            signInBtn.setText(spanUtils.create());

            signInTip.setText("请稍后");
            signInTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.practice_sign_tips_wait_icon), null, null, null);
            signInLocation.setText("暂未获取到定位");
            signInRestartLocation.setVisibility(View.VISIBLE);
            signInArea.setVisibility(View.GONE);

        } else { //已签到
            if (StringUtils.isNotEmpty(mData.getSignOutLatitude())) {
                latLng = new LatLng(Double.parseDouble(mData.getSignOutLatitude()), Double.parseDouble(mData.getSignOutLongitude()));
                latLonPoint = new LatLonPoint(Double.parseDouble(mData.getSignOutLatitude()), Double.parseDouble(mData.getSignOutLongitude()));
                aCircle = aMap.addCircle(new CircleOptions()
                        .center(latLng)
                        .radius(mData.getSignOutRadius())
                        .fillColor(Color.argb(85, 240, 137, 135))
                        .strokeColor(Color.argb(100, 240, 137, 135))
                        .strokeWidth(1));
            }
            signBtn.setText("立即签退");

            signInDot.setImageResource(R.color.global_base);
            signInDot.setVisibility(View.VISIBLE);
            signOutDot.setVisibility(View.VISIBLE);
            divider.setVisibility(View.VISIBLE);
            if (mData.getActSignType() == 0) {
                signInTxt.setVisibility(View.VISIBLE);
                signOutTxt.setVisibility(View.VISIBLE);
            }

            signInBtn.setVisibility(View.GONE);
            signInArea.setVisibility(View.GONE);
            signInRestartLocation.setVisibility(View.GONE);
            signInLocation.setVisibility(View.GONE);
            signInTip.setVisibility(View.GONE);

            signInAddress.setVisibility(View.VISIBLE);
            signInAddress.setText(mData.getVolSignInfo().getSignInAddr());

            signInTime.setVisibility(View.VISIBLE);
            signInTime.setText("打卡签到时间：" + DateUtils.translateToHHmmss(mData.getVolSignInfo().getSignTime()));

            if (mData.getVolSignInfo() != null && StringUtils.isNotEmpty(mData.getVolSignInfo().getSignOutTime())) { //已签退
                signOutDot.setImageResource(R.color.global_base);
                divider.setImageResource(R.color.global_base);

                signBtn.setEnabled(false);
                signBtn.setText("已签退");
                signOutBtn.setVisibility(View.GONE);
                signOutArea.setVisibility(View.GONE);
                signOutRestartLocation.setVisibility(View.GONE);
                signOutLocation.setVisibility(View.GONE);
                signOutTip.setVisibility(View.GONE);

                signOutAddress.setVisibility(View.VISIBLE);
                signOutAddress.setText(mData.getVolSignInfo().getSignOutAddr());

                signOutTime.setVisibility(View.VISIBLE);
                signOutTime.setText("打卡签退时间：" + DateUtils.translateToHHmmss(mData.getVolSignInfo().getSignOutTime()));
            } else {//未签退
                signOutDot.setImageResource(R.color.global_black_lv4);
                divider.setImageResource(R.color.practice_divider);

                SpanUtils spanUtils = new SpanUtils(this);
                spanUtils.append("定位中").setFontSize(30, true).setBold();
                signOutBtn.setText(spanUtils.create());

                signOutTip.setText("请稍后");
                signOutTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.practice_sign_tips_wait_icon), null, null, null);
                signOutLocation.setText("暂未获取到定位");
                signOutRestartLocation.setVisibility(View.VISIBLE);
                signOutArea.setVisibility(View.GONE);

                signOutLocation.setVisibility(View.VISIBLE);
                signOutTip.setVisibility(View.VISIBLE);
                signBtn.setEnabled(true);

            }
        }
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
        if (mData.getVolSignInfo().getIsSign() == 0) {
            signInBtn.setVisibility(View.VISIBLE);
            signInTip.setVisibility(View.VISIBLE);
            signInLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signInBtn.setText(spanUtils.create());

            signInTip.setText("请稍后");
            signInLocation.setText("暂未获取到定位");
        } else {
            signOutBtn.setVisibility(View.VISIBLE);
            signOutTip.setVisibility(View.VISIBLE);
            signOutLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signOutBtn.setText(spanUtils.create());

            signOutTip.setText("请稍后");
            signOutLocation.setText("暂未获取到定位");
        }
        if (mLocationClient != null) {
            mLocationClient.startLocation();
        }
    }

    @SuppressLint("SetTextI18n")
    @OnClick({R2.id.back_btn, R2.id.sign_in_btn, R2.id.sign_in_area, R2.id.sign_in_restart_location, R2.id.sign_out_btn, R2.id.sign_out_area, R2.id.sign_out_restart_location, R2.id.sign_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            if (mapLayout.getVisibility() == View.VISIBLE) {
                mapLayout.setVisibility(View.GONE);
                titleName.setText("GPS定位签到");
            } else {
                finish();
            }
        } else if (id == R.id.sign_in_btn) {
            if (signInBtn.getText().toString().contains("签到")) {
                mPresenter.signIn(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
            }
        } else if (id == R.id.sign_in_area) {
            mapLayout.setVisibility(View.VISIBLE);
            titleName.setText("查看范围");
        } else if (id == R.id.sign_in_restart_location) {
            signInRestartLocation.setVisibility(View.GONE);
            startLocation();
        } else if (id == R.id.sign_out_btn) {
            if (signOutBtn.getText().toString().contains("签退")) {
                if (DateUtils.isBeforeTime(mData.getRegistrationStart())) {
                    showToast("服务尚未开始，无法签退！");
                } else {
                    if (DateUtils.isBeforeTime(mData.getRegistrationDeadline())) {
                        new OtherDialog.Builder(PracticeSignHomeActivity.this)
                                .setContentView(R.layout.practice_dialog_edu_course_teacher)
                                .setText(R.id.title, "未到签退时间，提前签退将会影响您的服务时长，是否确认签退？")
                                .setDismissButton(R.id.negative_btn)
                                .setOnClickListener(R.id.positive_btn, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mPresenter.signOut(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
                                    }
                                }).show();
                    } else {
                        mPresenter.signOut(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
                    }
                }
            }
        } else if (id == R.id.sign_out_area) {
            mapLayout.setVisibility(View.VISIBLE);
            titleName.setText("查看范围");
        } else if (id == R.id.sign_out_restart_location) {
            signOutRestartLocation.setVisibility(View.GONE);
            startLocation();
        } else if (id == R.id.sign_btn) {
            if (signBtn.getText().toString().contains("签到")) {
                mPresenter.signIn(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
            } else {
                if (DateUtils.isBeforeTime(mData.getRegistrationStart())) {
                    showToast("服务尚未开始，无法签退！");
                } else {
                    if (DateUtils.isBeforeTime(mData.getRegistrationDeadline())) {
                        new OtherDialog.Builder(PracticeSignHomeActivity.this)
                                .setContentView(R.layout.practice_dialog_edu_course_teacher)
                                .setText(R.id.title, "未到签退时间，提前签退将会影响您的服务时长，是否确认签退？")
                                .setDismissButton(R.id.negative_btn)
                                .setOnClickListener(R.id.positive_btn, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mPresenter.signOut(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
                                    }
                                }).show();
                    } else {
                        mPresenter.signOut(mData.getId() + "", mData.getVol().getQrcode(), locationAddress);
                    }
                }

            }
        }
    }


    @Override
    protected void setListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_SIGN_HOME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_SIGN_HOME);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }

        if (timer != null) {
            timer.cancel();
        }
        BusFactory.getBus().unregister(this);
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                String currentTime = DateUtils.getHHmm();
                SpanUtils spanUtils = new SpanUtils(PracticeSignHomeActivity.this);
                if (StringUtils.isEmpty(beforeTime)) {
                    if (mData.getVolSignInfo().getIsSign() == 0) {
                        spanUtils.append("签到\n").setFontSize(20, true).setBold()
                                .append(currentTime).setFontSize(15, true);
                        signInBtn.setText(spanUtils.create());
                    } else {
                        spanUtils.append("签退\n").setFontSize(20, true).setBold()
                                .append(currentTime).setFontSize(15, true);
                        signOutBtn.setText(spanUtils.create());
                    }
                } else {
                    if (!currentTime.equals(beforeTime)) {
                        if (mData.getVolSignInfo().getIsSign() == 0) {
                            spanUtils.append("签到\n").setFontSize(20, true).setBold()
                                    .append(currentTime).setFontSize(15, true);
                            signInBtn.setText(spanUtils.create());
                        } else {
                            spanUtils.append("签退\n").setFontSize(20, true).setBold()
                                    .append(currentTime).setFontSize(15, true);
                            signOutBtn.setText(spanUtils.create());
                        }
                    }
                }
                beforeTime = currentTime;
            }
        }
    };

    /**
     * 签到成功
     */
    @Override
    public void signInSuccess() {
        showToast("签到成功！");
        BusFactory.getBus().post(new Event.PracticeActRefresh(1));
    }

    /**
     * 签退成功
     */
    @Override
    public void signOutSuccess() {
        showToast("签退成功！");
        BusFactory.getBus().post(new Event.PracticeActRefresh(1));
    }

    /**
     * 签到、签退失败
     */
    @Override
    public void signError(String msg) {
        showToast(msg);
    }


    /**
     * 激活定位
     *
     * @param onLocationChangedListener
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mData.getVolSignInfo().getIsSign() == 0) {
            signInBtn.setVisibility(View.VISIBLE);
            signInTip.setVisibility(View.VISIBLE);
            signInLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signInBtn.setText(spanUtils.create());

            signInTip.setText("请稍后");
            signInLocation.setText("暂未获取到定位");
        } else {
            signOutBtn.setVisibility(View.VISIBLE);
            signOutTip.setVisibility(View.VISIBLE);
            signOutLocation.setVisibility(View.VISIBLE);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("定位中").setFontSize(20, true).setBold();
            signOutBtn.setText(spanUtils.create());

            signOutTip.setText("请稍后");
            signOutLocation.setText("暂未获取到定位");
        }
        if (mLocationClient == null) {
            //初始化定位
            try {
                mLocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mLocationClient.setLocationListener(this);


            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            mLocationOption.setInterval(2000);

            mLocationOption.setOffset(true);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                locationAddress = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();

                currentLocation.setText("我的位置：" + locationAddress);
                if (mData.getActSignType() == 0) {
                    signInTxt.setVisibility(View.VISIBLE);
                    signOutTxt.setVisibility(View.VISIBLE);
                }

                signInDot.setVisibility(View.VISIBLE);
                signOutDot.setVisibility(View.VISIBLE);
                if (mData.getActSignType() == 0) {
                    divider.setVisibility(View.VISIBLE);
                }

                SpanUtils spanUtils = new SpanUtils(PracticeSignHomeActivity.this);
                if (mData.getVolSignInfo().getIsSign() == 0) {
                    spanUtils.append("签到\n").setFontSize(20, true).setBold()
                            .append(DateUtils.getHHmm()).setFontSize(15, true);
                    signInBtn.setText(spanUtils.create());
                } else {
                    spanUtils.append("签退\n").setFontSize(20, true).setBold()
                            .append(DateUtils.getHHmm()).setFontSize(15, true);
                    signOutBtn.setText(spanUtils.create());
                }
                mLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                if (mData.getVolSignInfo().getIsSign() == 0) {
                    if (StringUtils.isEmpty(aMapLocation.getAoiName())) {
                        signInLocation.setText(aMapLocation.getStreet() + aMapLocation.getStreetNum());
                    } else {
                        signInLocation.setText(aMapLocation.getAoiName());
                    }
                    signInRestartLocation.setVisibility(View.VISIBLE);
                    signInLocation.setVisibility(View.VISIBLE);
                    signInArea.setVisibility(View.VISIBLE);
                    if (aCircle.contains(mLatLng)) {
                        signBtn.setEnabled(true);
                        signInBtn.setEnabled(true);
                        signInTip.setText("已进入签到范围");
                        signInTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_on_icon), null, null, null);
                    } else {
                        signBtn.setEnabled(false);
                        signInBtn.setEnabled(false);
                        signInTip.setText("不在签到范围内");
                        signInTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_off_icon), null, null, null);
                    }
                } else {
                    if (mData.getVolSignInfo() != null && StringUtils.isEmpty(mData.getVolSignInfo().getSignOutTime())) {
                        if (StringUtils.isEmpty(aMapLocation.getAoiName())) {
                            signOutLocation.setText(aMapLocation.getStreet() + aMapLocation.getStreetNum());
                        } else {
                            signOutLocation.setText(aMapLocation.getAoiName());
                        }
                        signOutRestartLocation.setVisibility(View.VISIBLE);
                        signOutLocation.setVisibility(View.VISIBLE);
                        signOutTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_on_icon), null, null, null);
                        signOutArea.setVisibility(View.VISIBLE);
                        if (aCircle.contains(mLatLng)) {
                            signBtn.setEnabled(true);
                            signOutBtn.setEnabled(true);
                            signOutTip.setText("已进入签退范围");
                            signOutTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_on_icon), null, null, null);
                        } else {
                            signBtn.setEnabled(false);
                            signOutBtn.setEnabled(false);
                            signOutTip.setText("不在签退范围内");
                            signOutTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_off_icon), null, null, null);
                        }
                    }
                }
            } else {
                if (mData.getVolSignInfo().getIsSign() == 1 && StringUtils.isNotEmpty(mData.getVolSignInfo().getSignOutTime())) {
                    mLocationClient.stopLocation();
                } else {
                    mLocationClient.stopLocation();
                    showToast("请点击重新定位，再次尝试！");
                    if (mData.getVolSignInfo().getIsSign() == 0) {
                        signInArea.setVisibility(View.GONE);
                        signInBtn.setEnabled(false);
                        signBtn.setEnabled(false);
                        signInLocation.setText("定位失败");
                        signInRestartLocation.setVisibility(View.VISIBLE);
                        signInTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_off_icon), null, null, null);
                    } else {
                        signOutArea.setVisibility(View.GONE);
                        signOutBtn.setEnabled(false);
                        signBtn.setEnabled(false);
                        signOutLocation.setText("定位失败");
                        signOutRestartLocation.setVisibility(View.VISIBLE);
                        signOutTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(PracticeSignHomeActivity.this, R.drawable.practice_sign_tips_off_icon), null, null, null);
                    }
                    signInArea.setVisibility(View.VISIBLE);
                }
            }
            if (timer == null) {
                timer = new Timer();
                timer.schedule(timerTask, 0, 1000);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mapLayout.getVisibility() == View.VISIBLE) {
                mapLayout.setVisibility(View.GONE);
                titleName.setText("GPS定位签到");
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    /**
     * 地图加载成功
     */
    @Override
    public void onMapLoaded() {
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        builder.include(latLng);
        if (mLatLng != null) {
            builder.include(mLatLng);
        }
        LatLngBounds build = builder.build();
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(build, 20));

        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);

        geocoderSearch.getFromLocationAsyn(query);
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        String locationName;
        if (i == 1000) {
            String formatAddress = regeocodeAddress.getFormatAddress();
            if (formatAddress.contains("市")) {
                locationName = formatAddress.substring(formatAddress.indexOf("市") + 1);
            } else {
                locationName = formatAddress;
            }

        } else {
            if (mData.getVolSignInfo().getIsSign() == 0) {
                locationName = "签到地址";
            } else {
                locationName = "签退地址";
            }
        }

        if (marker == null) {
            marker = aMap.addMarker(new MarkerOptions().position(latLng).title(locationName).draggable(false).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), R.drawable.practice_sign_location_point_icon))));
            marker.setAnchor(0.5f, 0.5f);
            marker.showInfoWindow();
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeSignRefresh event) {
        if (event != null) {
            mData = event.getBean();
            setView();
        }
    }

}
